package com.vsd.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.demo.dialet.PaginationSupport;
import com.demo.domain.Message;
import com.demo.util.SqlUtils;
import com.vsd.daoEx.model.MessageEx;
import com.vsd.repository.MessageRepository;
import com.vsd.service.MessageService;

@Service
@Transactional
public class MessageServiceImpl implements MessageService {

	@SuppressWarnings("unused")
	private static final Logger LOGGER = LoggerFactory
			.getLogger(MessageServiceImpl.class);
	
	@Autowired
	JdbcTemplate jdbcTemplate;
	
	@Autowired
	private MessageRepository messageRepository;

	@Override
	public Page<Message> findAll(Pageable p) {
		// TODO Auto-generated method stub
		return messageRepository.findAll(p);
	}

	@Override
	public void delById(String id) {
		// TODO Auto-generated method stub
		messageRepository.delete(id);
	}

	@Override
	public Message findOne(String id) {
		// TODO Auto-generated method stub
		return messageRepository.findOne(id);
	}

	@Override
	public int updateByPrimaryKeySelective(Message m) {
		// TODO Auto-generated method stub
		try {
			String sql = SqlUtils.update(m, true, " where id = '"+m.getId()+"'");
			return jdbcTemplate.update(sql);
		} catch (Exception e) {
			return 0;
		}
		
		
	}

	@Override
	public void save(Message m) {
		// TODO Auto-generated method stub
		messageRepository.save(m);
	}

	@Override
	public List<MessageEx> selectExList(String areaCode, Sort sort) {
		// TODO Auto-generated method stub
		String sql = "select m.*,c.name as cityName from b_message m left join f_city c on m.area_code = c.code where 1=1 ";
		
		if(StringUtils.isNotBlank(areaCode)){
			sql+="and m.area_code = '"+areaCode+"'";
		}
		sql+=" order by m.create_time desc";
		
		sql = PaginationSupport.initPage(sql, jdbcTemplate);
		
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		List<MessageEx> ret = new ArrayList<>();
		for (Map<String, Object> map : maps) {
			MessageEx ex = new MessageEx();
			SqlUtils.transMap2Bean2(map, ex);
			ret.add(ex);
		}
		return ret;
	}
	
	
}
